/*
 * Copyright 1999-2019 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xuecheng.content.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.xuecheng.content.constant.SentinelConstant;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Configuration
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void doInit() {
        initCustomizedApis();
        initGatewayRules();
    }

    /**
     * 初始化自定义限流api资源
     */
    private void initCustomizedApis() {
        Set<ApiDefinition> definitions = new HashSet<>();
        ApiDefinition contentApi = new ApiDefinition("customized_content_api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    //add(new ApiPathPredicateItem().setPattern("/ahas"));
                    add(new ApiPathPredicateItem().setPattern("/content/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition mediaApi = new ApiDefinition("customized_media_api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/media/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition ordersApi = new ApiDefinition("customized_orders_api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/orders/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition searchApi = new ApiDefinition("customized_search_api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/search/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition learningApi = new ApiDefinition("customized_learning_api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/learning/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        definitions.add(contentApi);
        definitions.add(mediaApi);
        definitions.add(ordersApi);
        definitions.add(searchApi);
        definitions.add(learningApi);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }

    /**
     * 初始化各模块的限流策略
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();

        rules.add(new GatewayFlowRule("customized_content_api")
                .setCount(SentinelConstant.TEN)
                .setIntervalSec(SentinelConstant.ONE)
                .setBurst(SentinelConstant.FIVE)
                //从请求中提取参数的策略，URL模式，提取请求的参数为courseId
                .setParamItem(new GatewayParamFlowItem()
                        .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
                        .setFieldName("courseId"))
        );
        rules.add(new GatewayFlowRule("customized_media_api")
                .setCount(SentinelConstant.TEN)
                .setIntervalSec(SentinelConstant.ONE)
                .setBurst(SentinelConstant.FIVE)
        );
        rules.add(new GatewayFlowRule("customized_orders_api")
                .setCount(SentinelConstant.TEN)
                .setIntervalSec(SentinelConstant.ONE)
                .setBurst(SentinelConstant.FIVE)
        );
        rules.add(new GatewayFlowRule("customized_search_api")
                .setCount(SentinelConstant.TEN)
                .setIntervalSec(SentinelConstant.ONE)
                .setBurst(SentinelConstant.FIVE)
        );
        rules.add(new GatewayFlowRule("customized_learning_api")
                .setCount(SentinelConstant.TEN)
                .setIntervalSec(SentinelConstant.ONE)
                .setBurst(SentinelConstant.FIVE)
        );
        GatewayRuleManager.loadRules(rules);
    }
    //按照路由进行限流
/**
 private void initGatewayRules() {
 Set<GatewayFlowRule> rules = new HashSet<>();
 rules.add(new GatewayFlowRule("aliyun_route")
 .setCount(10)
 .setIntervalSec(1)
 );
 rules.add(new GatewayFlowRule("aliyun_route")
 .setCount(2)
 .setIntervalSec(2)
 .setBurst(2)
 .setParamItem(new GatewayParamFlowItem()
 .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
 )
 );
 rules.add(new GatewayFlowRule("httpbin_route")
 .setCount(10)
 .setIntervalSec(1)
 .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)
 .setMaxQueueingTimeoutMs(600)
 .setParamItem(new GatewayParamFlowItem()
 .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
 .setFieldName("X-Sentinel-Flag")
 )
 );
 rules.add(new GatewayFlowRule("httpbin_route")
 .setCount(1)
 .setIntervalSec(1)
 .setParamItem(new GatewayParamFlowItem()
 .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
 .setFieldName("pa")
 )
 );
 rules.add(new GatewayFlowRule("httpbin_route")
 .setCount(2)
 .setIntervalSec(30)
 .setParamItem(new GatewayParamFlowItem()
 .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
 .setFieldName("type")
 .setPattern("warn")
 .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
 )
 );

 rules.add(new GatewayFlowRule("some_customized_api")
 .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
 .setCount(5)
 .setIntervalSec(1)
 .setParamItem(new GatewayParamFlowItem()
 .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)
 .setFieldName("pn")
 )
 );
 GatewayRuleManager.loadRules(rules);
 }

 */
}
